package org.example.shoppingmall.util;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class HikariUtil {
        private static String jdbcUri, jdbcUsername, jdbcPassword, jdbcClassName;
        private static HikariConfig config = null;
        private static HikariDataSource dataSource = null;

        static
        {
            try
            {
                InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
                Properties prop = new Properties();
                prop.load(is);
                jdbcClassName = prop.getProperty("jdbc.className");
                jdbcUsername = prop.getProperty("jdbc.username");
                jdbcPassword = prop.getProperty("jdbc.password");
                jdbcUri = prop.getProperty("jdbc.uri");
                config = new HikariConfig();
                config.setPoolName("HikariPool");
                config.setJdbcUrl(jdbcUri);
                config.setUsername(jdbcUsername);
                config.setPassword(jdbcPassword);
                config.setDriverClassName(jdbcClassName);
                config.setMaximumPoolSize(20);
                config.setMinimumIdle(2);
                dataSource = new HikariDataSource(config);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        public static Connection getConn() throws SQLException
        {
            return dataSource.getConnection();
        }

        public static void release(ResultSet rs, PreparedStatement ps, Connection conn) {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        public static void close()
        {
            if(dataSource != null)
            {
                dataSource.close();
            }
        }
    }


